package com.yanqu.road.server.cross3server.cmd.washe;

import com.yanqu.road.entity.enums.eSeasonRewardType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.rank.xrank.XSeasonUserRank;
import com.yanqu.road.logic.pb.XRankPb;
import com.yanqu.road.logic.xlogic.rank.season.XSeasonUserRankListModel;
import com.yanqu.road.logic.xlogic.rank.season.XSeasonUserRankMap;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.activity.WasheProto;
import com.yanqu.road.server.cmd.CrossCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.cross3server.manager.Cross3XRankMgr;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.protocol.Cross3Protocol;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.utils.YanQuMessageUtils;

import java.util.List;

@Cmd(code = Cross3Protocol.C3_WASHE_GET_RANK_RECORD_FROM_GAME, desc = "瓦舍获取自己区服玩家排名")
public class Cross3WasheGetRankRecordFromGameCmd extends CrossCommand {

    private int systemId = eSystemId.WasheActivity.getValue();
    private int seasonId;
    private int type = eSeasonRewardType.WasheScoreRank.getIntValue();
    private String rangeKey;

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        WasheProto.CrossWasheGetRankRecordReqMsg reqMsg = WasheProto.CrossWasheGetRankRecordReqMsg.parseFrom(packet.getBytes());
        seasonId = reqMsg.getSeasonId();
        rangeKey = reqMsg.getRangeKey();
        type = reqMsg.getRankType();
        return true;
    }

    @Override
    public void execute(YanQuMessage packet) throws Exception {
        if(0 == type){
            type = eSeasonRewardType.WasheScoreRank.getIntValue();
        }
        XSeasonUserRankMap seasonUserRankMap = Cross3XRankMgr.getSeasonUserRankMap();
        XSeasonUserRankListModel seasonUserRankListModel = seasonUserRankMap.getUserRankListModel(systemId, seasonId, type, rangeKey);
        List<XSeasonUserRank> allRankList = seasonUserRankListModel.getAllRankList();

        WasheProto.CrossWasheGetRankRecordRespMsg.Builder builder = WasheProto.CrossWasheGetRankRecordRespMsg.newBuilder();
        int rankNum = 0;
        for (XSeasonUserRank rank : allRankList) {
            rankNum++;
            if (rank.getServerId() == serverId) {
                builder.addUserId(rank.getUserId());
                builder.addRank(rankNum);
            }
        }

        if (allRankList.size() > 0) {
            XSeasonUserRank topRank = allRankList.get(0);
            builder.setTopRank(XRankPb.parseXUserRankMsg(topRank, false));
        }
        builder.setRankType(type);
        YanQuMessage message = YanQuMessageUtils.buildMessage(GameProtocol.S_WASHE_GET_RANK_RECORD_FROM_CROSS, builder);
        MessageHelper.sendPacket(serverId, 0, message);
    }

    @Override
    public void sendData() {

    }
}
